package com.own.component.netty.core;

import com.own.component.autoconfig.property.netty.NettyProperties;
import com.own.component.netty.handler.NettyMessageHandler;
import com.own.component.netty.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * NettyRunner
 *
 * @author chenxueli
 * @date 2021/4/9 9:30
 */
@Slf4j
@Component
public class NettyRunner implements ApplicationContextAware {

    @Resource
    private NettyProperties nettyProperties;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void start(ChannelHandler... handlers) throws Exception {
        var bossGroup = new NioEventLoopGroup();
        var workerGroup = new NioEventLoopGroup();
        try {
            var bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childOption(ChannelOption.SO_RCVBUF, 2097152);
            bootstrap.localAddress(new InetSocketAddress(nettyProperties.getIp(), nettyProperties.getPort()));
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    var pipeline = socketChannel.pipeline();
                    pipeline.addLast(handlers);
                }
            });
            var channel = bootstrap.bind().sync().channel();
            log.info("socket 服务启动，ip={},port={}", nettyProperties.getIp(), nettyProperties.getPort());
            channel.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void start() throws Exception {
        start(
                new HttpServerCodec(),
                new ChunkedWriteHandler(),
                new HttpObjectAggregator(65536),
                new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        if (msg instanceof FullHttpRequest fullHttpRequest) {
                            var uri = fullHttpRequest.uri();
                            if (!uri.equals(nettyProperties.getPath())) {
                                // 访问的路径不是 websocket的端点地址，响应404
                                ctx.channel().writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND))
                                        .addListener(ChannelFutureListener.CLOSE);
                                return;
                            }
                        }
                        super.channelRead(ctx, msg);
                    }
                },
                new WebSocketServerCompressionHandler(),
                new WebSocketServerProtocolHandler(nettyProperties.getPath(), null, true, nettyProperties.getMaxFrameSize()),
                applicationContext.getBean(NettyMessageHandler.class),
                new NettyServerHandler()
        );
    }

}
